/**
 * 项目名称（软件名称）：忠旺机械物资管理系统(mms)                           *
 * 研发设计单位：忠旺机械设备制造有限公司机械设计院智能控制设计科设计与研发。   *
 * 版权所有：忠旺机械设备制造有限公司                                       *
 * 注：本项目的一切技术专利，使用规范归解释权由忠旺机械设备制造有限公司所有。   *
 * 软件版本：Ver 1.0.0                                                   *
 * 文件路径：com.zhongwang.mms.module.buy.service                        *
 * 创建时间：2020年08月11日 18时05分                                      *
 * ======================================================================
 * 路径
 * <p>
 * 路径
 * <p>
 * 路径
 **/
/**
 * 路径
 **/
package com.zhongwang.mms.module.buy.service;
/**
 * 引包
 **/

import com.zhongwang.mms.base.BaseService;
import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.gen.entity.*;
import com.zhongwang.mms.gen.mapper.BChangeReceiveLogMapper;
import com.zhongwang.mms.module.buy.dao.ChangeDao;
import com.zhongwang.mms.module.buy.model.ChangeDataModel;
import com.zhongwang.mms.module.buy.model.ShopPlanChangeReceiveModel;
import com.zhongwang.mms.util.BeanUtil;
import com.zhongwang.mms.util.LogFormatUtil;
import com.zhongwang.mms.util.ShiroUtils;
import com.zhongwang.mms.util.StringUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
@Log4j2
/**
 *@name: PurchasePlanChangeManagementService
 *@description: 采购计划变更管理业务逻辑层
 *@author: 徐一贺
 *@coddingDate: 2020/8/11 18:05
 *@version: v1.0
 **/
public class PurchasePlanChangeManagementService extends BaseService {
    @Autowired
    private ChangeDao changeDao;
    @Autowired
    private BChangeReceiveLogMapper bChangeReceiveLogMapper;

    /**
     * @name: receiveList
     * @description: 获取变更接收列表
     * @param: [param] 检索参数
     * @returnType: com.zhongwang.mms.common.JsonResult
     * @author: 徐一贺
     * @coddingDate: 2020/8/11 19:54
     * @version: v1.0
     **/
    public List<ShopPlanChangeReceiveModel> receiveList(ShopPlanChangeReceiveModel param) {
        List<ShopPlanChangeReceiveModel> list = new ArrayList<>();
        try {
            param.setChangeMark(1);
            list = changeDao.receiveList(param);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return list;
    }

    /**
     * @name: planList
     * @description: 获取接收变更计划列表
     * @param: [param]
     * @returnType: com.zhongwang.mms.common.JsonResult
     * @author: 徐一贺
     * @coddingDate: 2020/8/12 9:49
     * @version: v1.0
     **/
    public ChangeDataModel planList(ShopPlanChangeReceiveModel param) {
        ChangeDataModel changeDataModel = changeDao.getSheetInfoAndAuditInfo(param.getId());
        changeDataModel.setList(changeDao.planList(param));
        changeDataModel.setBefore(changeDao.getBeforeChangePlanById(param.getChangeId()));
        changeDataModel.setAfter(changeDao.getAfterChangePlanById(param.getChangeId()));
        changeDataModel.setResultId(param.getId());
        return changeDataModel;
    }

    /**
     * @name: getChangePlan
     * @description: 根据rppId获取变更数据
     * @param: [param]
     * @returnType: com.zhongwang.mms.module.buy.model.ShopPlanChangeReceiveModel
     * @author: 徐一贺
     * @coddingDate: 2020/8/12 20:02
     * @version: v1.0
     **/
    public ShopPlanChangeReceiveModel getChangePlan(ShopPlanChangeReceiveModel param) {
        return changeDao.getChangePlan(param);
    }

    /**
     * @name: saveChange
     * @description: 保存修改
     * @param: [param]
     * @returnType: com.zhongwang.mms.common.JsonResult
     * @author: 徐一贺
     * @coddingDate: 2020/8/13 8:20
     * @version: v1.0
     */
    public JsonResult saveChange(List<ShopPlanChangeReceiveModel> list, String clientIp) {
        JsonResult jsonResult = new JsonResult();
        try {
            Integer resultId = 0;
            if (list.size() > 0) {
                ShopPlanChangeReceiveModel first = list.get(0);
                first.setRppResultId(changeDao.getBReportPlanByRppId(list.get(0).getId()).getRppResultId());
                String crlChangeReason = changeDao.getPdmRepResultByPrimaryKey(list.get(0).getRppResultId()).getChangeReason();
                //循环应用变更信息
                for (int i = 0; i < list.size(); i++) {
                    ShopPlanChangeReceiveModel beforeObj = new ShopPlanChangeReceiveModel();
                    //拷贝操作日志使用对象变更前
                    BeanUtil.copy(changeDao.getBReportPlanByRppId(list.get(i).getId()), beforeObj);
                    if (beforeObj.getRppUseStore() == null || beforeObj.getRppUseStore().equals(0)) {
                        beforeObj.setRppUseStoreStr("否");
                    } else {
                        beforeObj.setRppUseStoreStr("是");
                    }
                    //获取被变更对象信息
                    ShopPlanChangeReceiveModel before = changeDao.getBReportPlanByRppId(list.get(i).getId());
                    if (resultId == 0) {
                        resultId = before.getRppResultId();
                    }
                    before.setRppMatDesc(list.get(i).getMalDesc());
                    before.setRppNum(list.get(i).getNum());
                    before.setRppStandardNo(list.get(i).getStandard());
                    before.setRppUnit(list.get(i).getUnit());
                    before.setRppBrand(list.get(i).getBrand());
                    before.setRppRemark(list.get(i).getRemark());
                    before.setRppDiagram(list.get(i).getDiagram());
                    before.setRppAssistType(list.get(i).getAssistType());
                    before.setRppUseStore(list.get(i).getUseStore());
                    before.setRppExtendUrl(list.get(i).getUrl());
                    if (!StringUtils.replaceBlank(before.getRppMatDesc().trim()).equals(StringUtils.replaceBlank(list.get(i).getMalDesc().trim()))) {
                        before.setRppChangeMark(1);
                    }
                    before.setRppChange(crlChangeReason);
                    before.setRppExtendUrl(changeDao.getUrlByRppResultId(before.getRppResultId()));
                    //变更对象信息
                    changeDao.updateByChange(before);
                    //获取变更后的信息 操作日志使用
                    ShopPlanChangeReceiveModel afterObj = changeDao.getBReportPlanByRppId(list.get(i).getId());
                    if (list.get(i).getRppSrcId() != null) {
                        ShopPlanChangeReceiveModel parentObject = changeDao.getBReportPlanByRppId(list.get(i).getRppSrcId());
                        //如果父级ID是old被拆分的则根据子级修改父级的数量
                        if (list.get(i).getRppSplitPlanType().equals("new") && parentObject.getRppSplitPlanType().equals("old")) {
                            before.setRppId(list.get(i).getRppSrcId());
                            Double childTotalNum = changeDao.getChildTotalNum(list.get(i).getRppSrcId());
                            before.setRppNum(childTotalNum);
                            changeDao.updateRppNumByRppId(list.get(i).getRppSrcId(), childTotalNum);
                        }
                    }
                    if (afterObj.getRppUseStore() == null || afterObj.getRppUseStore().equals(0)) {
                        afterObj.setRppUseStoreStr("否");
                    } else {
                        afterObj.setRppUseStoreStr("是");
                    }
                    if (!StringUtils.replaceBlank(beforeObj.getRppMatDesc().trim()).equals(StringUtils.replaceBlank(afterObj.getRppMatDesc().trim()))) {
                        //记录变更日志
                        //变更前
                        BReportPlanChange bReportPlanChange = new BReportPlanChange();
                        bReportPlanChange.setRpcRppId(beforeObj.getRppId());
                        bReportPlanChange.setRpcMatDesc(beforeObj.getRppMatDesc());
                        bReportPlanChange.setRpcMatCode(beforeObj.getSppSapCode());
                        bReportPlanChange.setRpcNum(beforeObj.getRppNum());
                        bReportPlanChange.setRpcUnit(beforeObj.getRppUnit());
                        bReportPlanChange.setRpcStandardNo(beforeObj.getRppStandardNo());
                        bReportPlanChange.setRpcBrand(beforeObj.getRppBrand());
                        bReportPlanChange.setRpcRemark(beforeObj.getRppRemark());
                        bReportPlanChange.setRpcDiagram(beforeObj.getRppDiagram());
                        bReportPlanChange.setRpcAssistType(beforeObj.getRppAssistType());
                        bReportPlanChange.setRpcUseStore(beforeObj.getRppUseStore());
                        bReportPlanChange.setRpcProjectCode(beforeObj.getRppProjectCode());
                        bReportPlanChange.setRpcProjectName(beforeObj.getRppProjectName());
                        bReportPlanChange.setRpcPart(beforeObj.getRppPart());
                        bReportPlanChange.setRpcTypeId(beforeObj.getRppTypeId());
                        bReportPlanChange.setRpcDesigner(beforeObj.getRppDesigner());
                        bReportPlanChange.setRpcTel(beforeObj.getRppDesignerTel());
                        //变更后
                        bReportPlanChange.setRpcNewMatDesc(afterObj.getRppMatDesc());
                        bReportPlanChange.setRpcNewMatCode(afterObj.getSppSapCode());
                        bReportPlanChange.setRpcNewNum(afterObj.getRppNum());
                        bReportPlanChange.setRpcNewUnit(afterObj.getRppUnit());
                        bReportPlanChange.setRpcNewStandardNo(afterObj.getRppStandardNo());
                        bReportPlanChange.setRpcNewBrand(afterObj.getRppBrand());
                        bReportPlanChange.setRpcNewRemark(afterObj.getRppRemark());
                        bReportPlanChange.setRpcNewDiagram(afterObj.getRppDiagram());
                        bReportPlanChange.setRpcNewAssistType(afterObj.getRppAssistType());
                        bReportPlanChange.setRpcNewUseStore(afterObj.getRppUseStore());
                        bReportPlanChange.setRpcNewProjectCode(afterObj.getRppProjectCode());
                        bReportPlanChange.setRpcNewProjectName(afterObj.getRppProjectName());
                        bReportPlanChange.setRpcNewPart(afterObj.getRppPart());
                        bReportPlanChange.setRpcNewTypeId(afterObj.getRppTypeId());
                        bReportPlanChange.setRpcNewDesigner(afterObj.getRppDesigner());
                        bReportPlanChange.setRpcNewTel(afterObj.getRppDesignerTel());
                        bReportPlanChange.setRpcChangeTime(new Date());
                        bReportPlanChange.setRpcReason(changeDao.getPdmRepResultByPrimaryKey(list.get(0).getRppResultId()).getChangeReason());
                        //记录变更日志
                        changeDao.insertBReportPlanChange(bReportPlanChange);
                    }
//                    saveChangeLog(beforeObj, 1, crlChangeReason, clientIp);
//                    //记录变更后的变更日志
//                    saveChangeLog(afterObj, 2, crlChangeReason, clientIp);
                    //记录操作日志
                    //操作日志生成器需要的字段与说明的映射文件
                    Map<String, String> fieldMap = new HashMap<String, String>();
                    fieldMap.put("rppMatDesc", "物料描述");
                    fieldMap.put("rppNum", "数量");
                    fieldMap.put("rppStandardNo", "标准号");
                    fieldMap.put("rppUnit", "单位");
                    fieldMap.put("rppBrand", "品牌");
                    fieldMap.put("rppRemark", "备注");
                    fieldMap.put("rppDiagram", "图号");
                    fieldMap.put("rppAssistType", "外协类型");
                    fieldMap.put("rppUseStoreStr", "是否使用库存");
                    //使用操作日志生成器生成bootstarp格式日志
                    String logContent = LogFormatUtil.getUpdateResult("变更信息如下", fieldMap, beforeObj, afterObj);
                    //记录日志
                    logService.saveLog("【采购变更管理】 ==》 接收变更", logContent);
                }
                //回写变更标识
                changeDao.updateRecMarkByChange(resultId, new Date());
                jsonResult.setType(JsonResult.ResultType.SUCCESS);
                jsonResult.setMsg("接收变更成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("接收变更失败！");
        }
        //使用事物结束锁表
        return jsonResult;
    }

    @Transactional(rollbackFor = Exception.class)
    /**
     *@name: saveChangeLog
     *@description: 记录变更日志
     *@param: [log] 日志
     *@returnType: void
     *@author: 徐一贺
     *@coddingDate: 2020/8/15 7:54
     *@version: v1.0
     **/
    void saveChangeLog(ShopPlanChangeReceiveModel logObj, Integer crlChangeType, String crlChangeReason, String ip) throws Exception {
        BChangeReceiveLog log = new BChangeReceiveLog();
        log.setCrlRppId(logObj.getRppId());
        log.setCrlMatDesc(logObj.getRppMatDesc());
        log.setCrlNum(logObj.getRppNum());
        log.setCrlUnit(logObj.getRppUnit());
        log.setCrlStandard(logObj.getRppStandardNo());
        log.setCrlBrand(logObj.getRppBrand());
        log.setCrlRemark(logObj.getRppRemark());
        log.setCrlDiagram(logObj.getRppDiagram());
        log.setCrlAssistType(logObj.getRppAssistType());
        log.setCrlUseStore(logObj.getRppUseStore());
        log.setCrlExtendUrl(logObj.getRppExtendUrl());
        log.setCrlSrcId(logObj.getRppSrcId());
        log.setCrlSplitPlanType(logObj.getRppSplitPlanType());
        log.setCrlAncestorsId(logObj.getRppAncestorsId());
        log.setCrlExtendUrl(logObj.getExtendUrl());
        log.setCrlChangeType(crlChangeType);
        log.setCrlChangeReason(crlChangeReason);
        log.setCrlReceiveDate(getDateTimeService.getSysDateTime());
        log.setCrlReceiveUid(ShiroUtils.getUserId());
        log.setCrlDriveIp(ip);
        bChangeReceiveLogMapper.insert(log);
    }

    /**
     *@name: planExist
     *@description: 判断C表中有没有此计划
     *@param: [id] 主键
     *@returnType: boolean
     *@author: 徐一贺
     *@coddingDate: 2020/9/2 11:55
     *@version: v1.0
     **/
    public boolean planExist(Integer id) {
        BReportPlan bReportPlan = changeDao.getBReportPlanByRppResultIdAndIsNotRemove(id);
        return bReportPlan != null;
    }

    /**
     *@name: getReasonChangeList
     *@description: 获取变更原因
     *@param: []
     *@returnType: java.util.List<com.zhongwang.mms.gen.entity.VwDictCommon>
     *@author: 徐一贺
     *@coddingDate: 2020/9/2 12:47
     *@version: v1.0
     **/
    public List<VwDictCommon> getReasonChangeList() {
        return changeDao.getReasonChangeList();
    }

    /**
     *@name: revokeChangeStatus
     *@description: 接收变更状态
     *@param: [id]
     *@returnType: com.zhongwang.mms.common.JsonResult
     *@author: 徐一贺
     *@coddingDate: 2020/9/4 15:27
     *@version: v1.0
     **/
    public JsonResult revokeChangeStatus(Integer id) {
        JsonResult jsonResult = new JsonResult();
        try {
            BReportPlan bReportPlan = changeDao.getBReportPlanByRppResultIdAndIsNotRemove(id);
            if (bReportPlan.getRppSppId() != null && bReportPlan.getRppSppId() != 0) {
                jsonResult.setType(JsonResult.ResultType.ERROR);
                jsonResult.setMsg("该计划已有采购计划无法撤销！请把该计划对应的采购计划删除并把计划撤销到正常提报未提交状态才可撤销！");
                return jsonResult;
            }
            if ((bReportPlan.getRppSppId() == null || bReportPlan.getRppSppId() == 0) && (bReportPlan.getRppStatus() != null && bReportPlan.getRppStatus() == 3) && (bReportPlan.getRppUseStock() != null && bReportPlan.getRppUseStock() == 2)) {
                jsonResult.setType(JsonResult.ResultType.ERROR);
                jsonResult.setMsg("该计划已提交无法撤销！请把该计划撤销到正常提包未提交状态才可撤销！");
                return jsonResult;
            }
            if ((bReportPlan.getRppSppId() == null || bReportPlan.getRppSppId() == 0) && (bReportPlan.getRppStatus() != null && bReportPlan.getRppStatus() == 2) && (bReportPlan.getRppUseStock() != null && bReportPlan.getRppUseStock() == 1) && (bReportPlan.getRppIsFlag() != null && bReportPlan.getRppIsFlag() == 1)) {
                jsonResult.setType(JsonResult.ResultType.ERROR);
                jsonResult.setMsg("该计划已提交无法撤销！该计划已指定库存，请清空指定后撤销！");
                return jsonResult;
            }
            changeDao.updateVwPdmRepResultChangeMarkAndRecMarkAndChangeRecTime(id);
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("撤销成功");
        } catch (Exception e) {
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("撤销失败");
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return jsonResult;
    }

    /**
     *@name: checkChangeMark
     *@description: 判断计划是否已撤销
     *@param: [id]
     *@returnType: com.zhongwang.mms.common.JsonResult
     *@author: 徐一贺
     *@coddingDate: 2020/9/4 15:27
     *@version: v1.0
     **/
    public JsonResult checkChangeMark(Integer id) {
        JsonResult jsonResult = new JsonResult();
        try {
            VwPdmRepResult changeModel = changeDao.getVwPdmRepResultByIdAndReceived(id);
            if (changeModel == null) {
                jsonResult.setType(JsonResult.ResultType.SUCCESS);
            } else {
                jsonResult.setType(JsonResult.ResultType.ERROR);
                jsonResult.setMsg("此计划已撤销");
            }
        } catch (Exception e) {
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("撤销失败");
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return jsonResult;
    }

    /**********************************************
     * @title: checkEmployIsRecipient
     * @description: 检测该物控员是不是 计划接收者
     * @param:
     * @return:
     * @author: 徐一贺
     * @date: 2020/9/18 14:42
     * @versron: ver 1.0
     **********************************************
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult checkEmployIsRecipient(String empName) {
        JsonResult jsonResult = new JsonResult();
        try {
            TEmploy tEmploy = changeDao.getTEmployByNameAndType(empName);
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setData(tEmploy != null);
            return jsonResult;
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error(ex.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("系统错误，请联系系统管理员！");
        }
        return jsonResult;
    }
}
